using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using AutoMapper;

namespace Rabbit3.Api.Services
{
    /// <summary>
    /// 简化的优化基础服务类
    /// </summary>
    public abstract class OptimizedBaseService
    {
        protected readonly ISqlSugarClient _db;
        protected readonly IMapper _mapper;
        protected readonly IMemoryCache _cache;
        protected readonly ILogger _logger;

        // 缓存键前缀
        protected const string CACHE_PREFIX_TRACEABILITY = "traceability_";
        protected const string CACHE_PREFIX_FARMING = "farming_";
        protected const string CACHE_PREFIX_SLAUGHTER = "slaughter_";
        protected const string CACHE_PREFIX_PROCESSING = "processing_";
        protected const string CACHE_PREFIX_ENTERPRISE = "enterprise_";
        protected const string CACHE_PREFIX_SUPPLIER = "supplier_";

        // 缓存过期时间
        protected static readonly TimeSpan CACHE_EXPIRY = TimeSpan.FromMinutes(30);
        protected static readonly TimeSpan SHORT_CACHE_EXPIRY = TimeSpan.FromMinutes(5);

        protected OptimizedBaseService(ISqlSugarClient db, IMapper mapper, IMemoryCache cache, ILogger logger)
        {
            _db = db;
            _mapper = mapper;
            _cache = cache;
            _logger = logger;
        }

        /// <summary>
        /// 获取或设置缓存
        /// </summary>
        protected async Task<T?> GetOrSetCacheAsync<T>(string key, Func<Task<T?>> factory, TimeSpan? expiry = null) where T : class
        {
            if (_cache.TryGetValue(key, out T? cachedValue))
            {
                return cachedValue;
            }

            var value = await factory();
            if (value != null)
            {
                _cache.Set(key, value, expiry ?? CACHE_EXPIRY);
            }
            return value;
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        protected void RemoveCache(string key)
        {
            _cache.Remove(key);
        }

        /// <summary>
        /// 批量移除缓存
        /// </summary>
        protected void RemoveCachePattern(string pattern)
        {
            // 简化版本：只移除已知的缓存键
            // 在实际应用中，可以使用Redis等分布式缓存来支持模式匹配
            _logger.LogInformation($"缓存模式清理请求: {pattern}");
        }

        /// <summary>
        /// 并行执行两个查询
        /// </summary>
        protected async Task<(T1?, T2?)> ExecuteParallelAsync<T1, T2>(
            Func<Task<T1?>> task1, 
            Func<Task<T2?>> task2)
        {
            var task1Result = task1();
            var task2Result = task2();
            await Task.WhenAll(task1Result, task2Result);
            return (await task1Result, await task2Result);
        }

        /// <summary>
        /// 并行执行三个查询
        /// </summary>
        protected async Task<(T1?, T2?, T3?)> ExecuteParallelAsync<T1, T2, T3>(
            Func<Task<T1?>> task1, 
            Func<Task<T2?>> task2, 
            Func<Task<T3?>> task3)
        {
            var task1Result = task1();
            var task2Result = task2();
            var task3Result = task3();
            await Task.WhenAll(task1Result, task2Result, task3Result);
            return (await task1Result, await task2Result, await task3Result);
        }

        /// <summary>
        /// 并行执行五个查询
        /// </summary>
        protected async Task<(T1?, T2?, T3?, T4?, T5?)> ExecuteParallelAsync<T1, T2, T3, T4, T5>(
            Func<Task<T1?>> task1, 
            Func<Task<T2?>> task2, 
            Func<Task<T3?>> task3,
            Func<Task<T4?>> task4,
            Func<Task<T5?>> task5)
        {
            var task1Result = task1();
            var task2Result = task2();
            var task3Result = task3();
            var task4Result = task4();
            var task5Result = task5();
            await Task.WhenAll(task1Result, task2Result, task3Result, task4Result, task5Result);
            return (await task1Result, await task2Result, await task3Result, await task4Result, await task5Result);
        }

        /// <summary>
        /// 优化的分页查询
        /// </summary>
        protected async Task<(List<T> Data, int TotalCount)> GetPagedDataAsync<T>(
            ISugarQueryable<T> query, 
            int pageIndex, 
            int pageSize, 
            string? orderBy = null) where T : class
        {
            // 并行执行总数查询和数据查询
            var countTask = query.CountAsync();
            var dataTask = query
                .OrderByDescending(x => orderBy ?? "CreatedAt")
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            await Task.WhenAll(countTask, dataTask);

            return (await dataTask, await countTask);
        }
    }
}